package com.suishoupai.xmb.service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * Created by caojian on 2017/3/30.
 */
@Service
public class QiniuService {

    @Value("${qiniu.access-key}")
    private String accesskey;
    @Value("${qiniu.secret-key}")
    private String secretKey;
    @Value("${qiniu.callback-url}")
    private String callbackUrl;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.down-domain}")
    private String downDomain;
    @Autowired
    private Auth auth;// 认证
    @Autowired
    private BucketManager bucketManager;// 资源管理

    @Bean
    public Auth auth() {
        return Auth.create(accesskey, secretKey);
    }

    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth);
    }

    /**
     * 获取商品上传凭证（调用前请检查参数合法性）
     *
     * @param saleId
     * @return
     */
    public String buildGoodsUploadToken(long saleId) {
        StringMap policy = new StringMap();
        policy.put("mimeLimit", "image/*");// 表示只允许上传图片
        policy.put("fsizeLimit", 1 * 1024 * 1024);// 限制为1兆
        policy.put("endUser", saleId + "");// 上传用户
        policy.put("insertOnly", 1);// 非0代表新增，不能覆盖
        policy.put("callbackFetchKey", 1);// 由本服务器决定key(key:七牛资源唯一ID)
        policy.put("callbackUrl", callbackUrl + "/sale/goods");// 上传成功后的回调地址
        policy.put("callbackBody", "saleId=$(endUser)&categoryId=$(x:categoryId)&name=$(x:name)&introduce=$(x:introduce)&number=$(x:number)&price=$(x:price)");// 回调内容
        long expires = 60 * 60;// 有效时长一小时
        String token = auth.uploadToken(bucket, null, expires, policy);
        return token;
    }

    /**
     * 商品修改凭证
     *
     * @param goodsId
     * @return
     */
    public String buildGoodsModifyToken(long goodsId) {
        StringMap policy = new StringMap();
        policy.put("mimeLimit", "image/*");// 表示只允许上传图片
        policy.put("fsizeLimit", 1 * 1024 * 1024);// 限制为1兆
        policy.put("endUser", goodsId + "");// 上传用户
        policy.put("insertOnly", 1);// 非0代表新增，不能覆盖
        policy.put("callbackFetchKey", 1);// 由本服务器决定key(key:七牛资源唯一ID)
        policy.put("callbackUrl", callbackUrl + "/sale/goods/" + goodsId + "/coverImage");// 上传成功后的回调地址
        policy.put("callbackBody", "goodsId=$(endUser)");// 回调内容
        long expires = 60 * 60;// 有效时长一小时
        String token = auth.uploadToken(bucket, null, expires, policy);
        return token;
    }

    /**
     * 商家店铺图
     *
     * @param saleId
     * @return
     */
    public String buildSaleCoverToken(long saleId) {
        StringMap policy = new StringMap();
        policy.put("mimeLimit", "image/*");// 表示只允许上传图片
        policy.put("fsizeLimit", 1 * 1024 * 1024);// 限制为1兆
        policy.put("endUser", saleId + "");// 上传用户
        policy.put("insertOnly", 1);// 非0代表新增，不能覆盖
        policy.put("callbackFetchKey", 1);// 由本服务器决定key(key:七牛资源唯一ID)
        policy.put("callbackUrl", callbackUrl + "/sale/" + saleId + "/coverImage");// 上传成功后的回调地址
        policy.put("callbackBody", "saleId=$(endUser)");// 回调内容
        long expires = 60 * 60;// 有效时长一小时
        String token = auth.uploadToken(bucket, null, expires, policy);
        return token;
    }

    /**
     * 删除七牛资源（调用前请检查参数合法性）
     *
     * @param key
     * @return true:删除成功
     */
    public boolean deleteKey(String key) {
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucket, key);
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            return r.statusCode == 612;// 612代表资源不存在（暂时理解为已被删除）
        }
        return true;
    }

    /**
     * 删除七牛资源（调用前请检查参数合法性）
     *
     * @param keys
     * @return true:删除成功
     */
    public boolean deleteKeys(List<String> keys) {
        // 创建Batch类型的operations对象
        BucketManager.Batch operations = new BucketManager.Batch();
        for (String key : keys) {
            operations.delete(bucket, key);
        }
        try {
            // 调用批量操作的batch方法
            Response res = bucketManager.batch(operations);
            return res.statusCode == 298 || res.statusCode == 200;
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            return r.statusCode == 612;// 612代表资源不存在（暂时理解为已被删除）
        }
    }

    /**
     * "image/" + UUID.randomUUID().toString();
     *
     * @return
     */
    public String buildImageKey() {
        return "image/" + UUID.randomUUID().toString();
    }

    public String getDownDomain() {
        return downDomain;
    }
}
